package com.jc.photo.ai;

import com.jc.photo.controller.vo.RateImageVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片评分服务（基于 Ollama / Spring AI）
 */
@Slf4j
@Service
public class OllamaImageScoringService implements AIService {

    @Resource(name = "ollamaChatClient")
    private ChatClient chatClient;

    /**
     * 批量分析并筛选图片，返回每张图片的评分信息列表
     */
    @Override
    public List<RateImageVO> rateImages(String inputFolder, String outputFolder, Double miniScore) {
        File inputDir = new File(inputFolder);
        File outputDir = new File(outputFolder);

        if (!inputDir.exists() || !inputDir.isDirectory()) {
            throw new IllegalArgumentException("输入目录不存在或不是一个文件夹: " + inputFolder);
        }

        if (!outputDir.exists()) {
            boolean created = outputDir.mkdirs();
            log.info("输出目录 {} 创建结果: {}", outputFolder, created);
        }

        log.info("开始扫描图片目录: {}", inputFolder);

        @SuppressWarnings("unchecked")
        List<File> imageFiles = (List<File>) FileUtils.listFiles(
                inputDir,
                new String[]{"jpg", "jpeg", "png", "gif", "bmp","JPG", "JPEG", "PNG", "GIF", "BMP"},
                false
        );

        log.info("发现 {} 张图片，开始分析...", imageFiles.size());

        List<RateImageVO> results = new ArrayList<>();

        for (File imageFile : imageFiles) {
            log.info("正在分析: {}", imageFile.getName());
            try {
                RateImageVO rateImageVO = analyzeAndScoreImage(imageFile);
                results.add(rateImageVO);

                Double score = rateImageVO.getScore();
                if (score != null && score >= 0) {
                    log.info("模型评分: {}/10 - 文件: {}", String.format("%.1f", score), imageFile.getName());
                    if (score >= miniScore) {
                        FileUtils.copyFileToDirectory(imageFile, outputDir);
                        log.info("分数达标 (>= {}), 已复制到: {}", miniScore, outputFolder);
                    } else {
                        log.debug("分数未达标: {} < {}", score, miniScore);
                    }
                } else {
                    log.warn("未能从模型响应中提取有效分数: {}", imageFile.getName());
                }

            } catch (Exception e) {
                log.error("处理图片 {} 时发生异常", imageFile.getName(), e);
            }
        }

        log.info("分析完成。高分图片已保存至: {}", outputFolder);
        return results;
    }

    /**
     * 分析单张图片并返回评分对象
     */
    private RateImageVO analyzeAndScoreImage(File imageFile) {
        RateImageVO rateImageVO = new RateImageVO();
        rateImageVO.setFileName(imageFile.getAbsolutePath());
        return rateImageVO;
    }

    /**
     * 解析模型响应提取分数与备注（更鲁棒：支持中/英文“分数/Score”，使用正则提取数值）
     */
    private RateImageVO parseScoreRemark(File file, String response) {
        RateImageVO rateImageVO = new RateImageVO();
        rateImageVO.setFileName(file.getAbsolutePath());
        rateImageVO.setRemark(response == null ? "" : response);

        return rateImageVO;
    }
}
